package cn.zyjblogs.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;


/**
 * @author zhuyijun
 */
public class MyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //在bossGroup中添加一个日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch)  {
                            ChannelPipeline pipeline = ch.pipeline();
                            //因为是基于http协议，使用http的编解码器
                            pipeline.addLast(new HttpServerCodec())
                                    //以块方式写，添加 ChunkedWriteHandler 处理器
                                    .addLast(new ChunkedWriteHandler())
                                    /**
                                     * 说明
                                     * 1、http数据在传输过程中是分段的、HttpObjectAggregator，就可以将多个段聚合
                                     * 2、这就是为什么，当浏览器发送大量数据时，就会发出多次http请求
                                     *
                                     */
                                    .addLast(new HttpObjectAggregator(8192))
                                    /**
                                     *  说明
                                     *  1、对应websocket，他的数据是以帧（frame）形式传递
                                     *  2、可以看到WebSocketFrame 下面有六个子类
                                     *  3、浏览器请求时 ws://localhost:7000/xxx 请求路径
                                     *  4、WebSocketServerProtocolHandler 将http协议升级为ws协议
                                     *  5、 是通过状态码101 切换
                                     */
                                    .addLast(new WebSocketServerProtocolHandler("/hello"))
                                    /**
                                     * 自定义Handler，处理业务逻辑
                                     */
                                    .addLast(new MyTextWebSocketFrameHandler());

                        }
                    });
            //启动服务器
            ChannelFuture sync = bootstrap.bind(7000).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("服务端关闭");
        }
    }
}
